package com.base.common.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;

/**
 * @author sunli
 * @date 2010-8-12
 * @version $Id: Config.java 7 2011-07-15 04:24:04Z JiaqiangYan@gmail.com $
 */
public class Config {
	// map 存储配置信息
	private static Map<String, String> configMap = new ConcurrentHashMap<String, String>();
	// 调用初始化操作
	static {
		initConfig();
	}

	private Config() {
	}

	/**
	 * 初始化操作
	 * 
	 * @throws IOException
	 * 
	 */
	private static void initConfig() {
		File file;
		file = new File("config.properties");
		if (!file.exists()) {
			file = new File("config/config.properties");
		}

		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			Properties p = new Properties();
			p.load(in);

			for (Map.Entry<Object, Object> entry : p.entrySet()) {
				String key = (String) entry.getKey();
				String value = (entry.getValue() == null ? null : entry.getValue().toString());
				configMap.put(key, value);
			}

		} catch (FileNotFoundException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					throw new RuntimeException(e.getMessage(), e);
				}
			}
		}
	}

	/**
	 * 获取配置文件的某个键值的配置信息
	 * 
	 * @param key
	 *            键
	 * @return 值
	 */
	public static String getValue(String key) {
		return configMap.get(key);
	}

	public static int getIntValue(String key) {
		return Integer.parseInt(getValue(key));
	}

	public static long getLongValue(String key) {
		return Long.parseLong(getValue(key));
	}

	public static float getFloatValue(String key) {
		return Float.parseFloat(getValue(key));
	}

	public static double getDoubleValue(String key) {
		return Double.parseDouble(getValue(key));
	}

	/**
	 * 当值为1，或者true时，返回true
	 * 
	 * @param key
	 * @return
	 */
	public static boolean getBooleanValue(String key) {
		String value = getValue(key);
		if (StringUtils.isNotEmpty(value)) {
			value = value.toLowerCase();
			if (value.equals("true") || value.equals("1")) {
				return true;
			}
		}
		return false;
	}

	public synchronized static void reload() {
		initConfig();
	}

	public static Set<String> keySet() {
		return configMap.keySet();
	}
}
